/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.gidoo.websites.example;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.pages.RedirectPage;
import org.apache.wicket.protocol.http.WebApplication;
import org.gidoo.cms.jcr.JcrHelper;
import org.gidoo.cms.login.GidooCMSSession;
import org.gidoo.cms.view.ContentGenerationFailedException;
import org.gidoo.cms.view.ContentView;
import org.gidoo.cms.view.PathNotFoundException;

/**
 * The view of the example website.
 * @author thomas
 */
public class View extends ContentView
{

  Link lnkEnglish;
  Link lnkDeutsch;
  
  @Override
  protected void createAndAddComponents()
  {
    super.createAndAddComponents();
    
     lnkEnglish = new Link("lnkEnglish") {

      @Override
      public void onClick()
      {
        changeLanguage("en");
      }
    };
    add(lnkEnglish);
    
    lnkDeutsch = new Link("lnkDeutsch") {

    @Override
    public void onClick()
    {
      changeLanguage("de");
    }
    };
    add(lnkDeutsch);
  }
  
  private void changeLanguage(String lang)
  {
    try
    {
      String prefix = 
        ((WebApplication) getApplication()).getServletContext().getContextPath()
        + "/" + ((App) getApplication()).getCMSPath() + "/";
      
      String newUrl = prefix + lang + "/";
      if(currentPage != null)
      {
        Node rootNode = ((GidooCMSSession) getSession()).getJcrRootNode();

        String oldUrl = JcrHelper.getPartialURLForNode(rootNode, currentPage);

        String testUrl = lang + oldUrl.substring(2);
        
        if(JcrHelper.getPublishedPageByPath(testUrl, (GidooCMSSession) getSession()) != null)
        {        
          newUrl = prefix + testUrl;
        }
      }
      
      this.setResponsePage(new RedirectPage(newUrl));
    }
    catch (RepositoryException ex)
    {
      Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  @Override
  protected void generateSite(String path) throws PathNotFoundException, ContentGenerationFailedException
  {    
           
    if("".equals(path))
    {
      String lang = "en";

      if("de".equals(getLocale().getLanguage()))
      {
        lang = "de";
      }

      WebApplication app = (WebApplication) getApplication();

      // forward to language specific page
      this.setResponsePage(
        new RedirectPage(
        app.getServletContext().getContextPath() + 
        "/" + ((App) getApplication()).getCMSPath() + "/" + lang + "/"));
      return;
    }
      
    // select the right local
    Locale loc = getSession().getLocale();
    if(path.startsWith("de/"))
    {
      if(!loc.getLanguage().equals("de"))
      {
        getSession().setLocale(new Locale("de"));
      }
      lnkDeutsch.setEnabled(false);
      lnkEnglish.setEnabled(true);
    }
    else
    {
      if(!loc.getLanguage().equals("en"))
      {
        getSession().setLocale(new Locale("en"));
      }
      lnkDeutsch.setEnabled(true);
      lnkEnglish.setEnabled(false);
    }
   
    try
    {
      super.generateSite(path);
    }
    finally
    {
      generateMenu();
    }
  }

  @Override
  protected void generateTitle(Node page) throws ContentGenerationFailedException
  {
    try
    {
      title.setModelObject(page.getProperty("cms:title").getString() + " | " + getString("title"));
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
      throw new ContentGenerationFailedException(ex.getMessage());
    }
  }
  
  protected void generateMenu() throws ContentGenerationFailedException
  {
    try
    {
      Node root = ((GidooCMSSession) getSession()).getJcrRootNode();
      Locale loc = getSession().getLocale();
      String lang = loc.getLanguage();
      
      
      if(!"de".equals(lang) && !"en".equals(lang))
      {
        lang = "en"; // default language
      }
      
      List menuSections = new ArrayList();
      
      NodeIterator it = root.getNode("sections").getNodes();
      
      while(it.hasNext())
      {
        Node s = it.nextNode();
        if(s.getProperty("cms:url").getString().startsWith(lang) 
          && s.hasProperty("cms:xml"))
        {
          menuSections.add(s);
          
          List subList = new LinkedList();
          addPages(subList, s);
          
          if(subList.size() > 0)
          {
            menuSections.add(subList);
          }
          
        }
      }
      
      MenuPanel menuPanel = new MenuPanel("menuPanel", menuSections);
      
      add(menuPanel);
    }
    catch (RepositoryException ex)
    {
      Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
      throw(new ContentGenerationFailedException());
    }
  }
  
  private void addPages(List list, Node parentNode) throws RepositoryException
  {
    if(list == null || parentNode == null)
    {
      return;
    }
    
    NodeIterator it = parentNode.getNodes();
    
    while(it.hasNext())
    {
      Node c = it.nextNode();
      if(c.hasProperty("cms:xml"))
      {
        List subList = new LinkedList();

        list.add(c);
        addPages(subList, c);
        
        if(subList.size() > 0)
        {
          list.add(subList);
        }
      }
    }
  }
  
}
